package com.jinlejia.bbs.help;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;

/**
 * @author 王进 on 2019/3/13.
 */

public final class CommonEvent {
    private CommonEvent(){
        //lock
    }
    private static CommonEvent event;
    public static CommonEvent obtain(){
        if (event==null){
            event = new CommonEvent();
        }
        return event;
    }

    /**
     * 退出社区模块，跳转至[inHome]首页
     */
    public void quit(View view){
        Class<?> clazz = null;
        try {
            clazz = Class.forName("com.jinlejia.erp.ui.common.MainActivity");
        } catch (ClassNotFoundException ignored) {
        }
        Context context = view.getContext();
        if (clazz==null){
            System.out.println("没有找到[inHome::MainActivity]@"+context.getClass().getCanonicalName());
            return;
        }
        Intent intent = new Intent();
        intent.setClass(context,clazz);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    private Activity getActivity(View view){
        if (view==null)return null;
        Context context = view.getContext();
        if (context instanceof Activity){
            return (Activity) context;
        }else {
            return getActivity(view.getRootView());
        }
    }

    public void back(View view){
        Activity activity = getActivity(view);
        if (activity!=null){
            if (activity instanceof BackFilter){
                boolean canBack = ((BackFilter) activity).onBack();
                if (!canBack && !activity.isFinishing()){
                    activity.finish();
                }
            }else {
                activity.finish();
            }
        }
    }

    public interface BackFilter{
        /**
         * 在关闭Activity之前，允许Activity做自己特殊的业务
         * @return true：消化掉Back事件 false:继续关闭Activity
         */
        boolean onBack();
    }

}
